<template>
  <div class="apicase-container">
    <div class="header-container">
      <div class="title">接口用例</div>
    </div>
    <div class="search-section">
      <search-bar @search="handleSearch" />
    </div>
    
    <!-- 表格部分 -->
    <el-table
      :data="tableData"
      style="width: 100%; background-color: transparent !important;"
      :border="false"
      :cell-style="{backgroundColor: 'transparent', border: 'none', padding: '12px 0'}"
      :header-cell-style="{backgroundColor: 'transparent', border: 'none', padding: '12px 0'}"
      class="transparent-table"
      height="calc(100vh - 200px)"
    >
      <template slot="empty">
        <empty-state />
      </template>
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
        header-align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="apiName"
        label="接口名称"
        min-width="150"
        align="center"
        header-align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="testPoint"
        label="测试点"
        min-width="200"
        align="center"
        header-align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="expectedResult"
        label="预期结果"
        min-width="200"
        align="center"
        header-align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
        header-align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        width="280"
        fixed="right"
        align="center"
        header-align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleRun(scope.row)">运行</el-button>
          <el-button
            size="mini"
            type="danger"
            :disabled="!hasLogs[scope.row.id]"
            @click="handleViewLogs(scope.row)">查看日志</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 加载中遮罩层 -->
    <div class="loading-overlay" v-if="isLoading">
      <div class="loading-content">
        <img src="@/assets/loading.png" alt="Loading" class="loading-image">
        <div class="loading-text">接口用例执行中...</div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑接口用例"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="transparent-dialog"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="接口名称">
          <el-input type="textarea" v-model="editForm.apiName" placeholder="请输入接口名称" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="测试点">
          <el-input type="textarea" v-model="editForm.testPoint" placeholder="请输入测试点" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="预期结果">
          <el-input type="textarea" v-model="editForm.expectedResult" placeholder="请输入预期结果" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 日志对话框 -->
    <el-dialog
      title="接口用例执行日志"
      :visible.sync="logDialogVisible"
      width="60%"
      :before-close="handleCloseLogDialog"
      :close-on-click-modal="false"
      custom-class="transparent-dialog"
    >
      <div class="log-content">
        <pre v-if="currentLogs" class="log-pre">{{ currentLogs }}</pre>
        <div v-else class="no-logs">暂无日志数据</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="logDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchBar from './SearchBar.vue'
import EmptyState from './EmptyState.vue'

export default {
  name: 'apicase',
  components: {
    SearchBar,
    EmptyState
  },
  data() {
    return {
      tableData: [
        {
          id: 1001,
          apiName: '/api/user/login',
          testPoint: '使用有效的用户名和密码登录',
          expectedResult: '返回状态码200，返回用户信息和token',
          createTime: '2023-10-15 09:30:45'
        },
        {
          id: 1002,
          apiName: '/api/user/login',
          testPoint: '使用无效的用户名登录',
          expectedResult: '返回状态码401，返回错误信息"用户名不存在"',
          createTime: '2023-10-15 09:35:22'
        },
        {
          id: 1003,
          apiName: '/api/user/register',
          testPoint: '注册新用户，所有必填字段均有效',
          expectedResult: '返回状态码201，返回新用户ID和成功消息',
          createTime: '2023-10-16 14:25:11'
        },
        {
          id: 1004,
          apiName: '/api/products',
          testPoint: '获取产品列表，使用分页参数page=1&limit=10',
          expectedResult: '返回状态码200，返回10条产品数据和总数量',
          createTime: '2023-10-17 11:05:33'
        },
        {
          id: 1005,
          apiName: '/api/products/search',
          testPoint: '搜索产品，使用关键词"手机"',
          expectedResult: '返回状态码200，返回包含关键词的产品列表',
          createTime: '2023-10-18 15:42:18'
        },
        {
          id: 1006,
          apiName: '/api/orders/create',
          testPoint: '创建订单，产品ID有效，库存充足',
          expectedResult: '返回状态码201，返回订单ID和订单详情',
          createTime: '2023-10-19 10:12:56'
        },
        {
          id: 1007,
          apiName: '/api/orders/create',
          testPoint: '创建订单，产品ID有效，库存不足',
          expectedResult: '返回状态码400，返回错误信息"库存不足"',
          createTime: '2023-10-19 10:15:30'
        },
        {
          id: 1008,
          apiName: '/api/user/profile',
          testPoint: '获取用户资料，使用有效的token',
          expectedResult: '返回状态码200，返回用户详细资料',
          createTime: '2023-10-20 16:08:22'
        },
        {
          id: 1009,
          apiName: '/api/user/logout',
          testPoint: '用户注销，使用有效的token',
          expectedResult: '返回状态码200，返回成功消息',
          createTime: '2023-10-21 09:55:47'
        },
        {
          id: 1010,
          apiName: '/api/payments/process',
          testPoint: '处理支付，使用有效的支付信息',
          expectedResult: '返回状态码200，返回支付确认信息和交易ID',
          createTime: '2023-10-22 14:33:09'
        }
      ], // 初始化为包含示例数据的数组
      originalTableData: [], // 用于存储原始数据
      dialogVisible: false, // 控制对话框显示
      loadingRows: {}, // 用于跟踪正在运行的用例
      isLoading: false, // 控制全局加载状态
      hasLogs: {}, // 用于记录哪些用例有日志
      logDialogVisible: false, // 控制日志对话框显示
      currentLogs: '', // 当前查看的日志内容
      currentCase: null, // 当前操作的用例
      editForm: {
        id: null,
        apiName: '',
        testPoint: '',
        expectedResult: ''
      }
    }
  },
  created() {
    // 保存原始数据
    this.originalTableData = [...this.tableData]
  },
  methods: {
    handleSearch(searchData) {
      // 重置数据
      let filteredData = [...this.originalTableData]

      // 处理第一个搜索条件
      if (searchData.first.condition && searchData.first.value) {
        filteredData = filteredData.filter(item => {
          const value = String(item[searchData.first.condition]).toLowerCase()
          return value.includes(searchData.first.value.toLowerCase())
        })
      }

      // 处理第二个搜索条件
      if (searchData.second.condition && searchData.second.value) {
        filteredData = filteredData.filter(item => {
          const value = String(item[searchData.second.condition]).toLowerCase()
          return value.includes(searchData.second.value.toLowerCase())
        })
      }

      // 更新表格数据
      this.tableData = filteredData
    },
    handleEdit(row) {
      // 打开编辑对话框并填充数据
      this.editForm = { ...row }
      this.dialogVisible = true
    },
    handleRun(row) {
      // 设置当前操作的用例
      this.currentCase = row
      
      // 设置全局loading状态为true
      this.isLoading = true
      
      // 处理运行操作
      console.log('运行', row)
      
      // 模拟API调用，3秒后恢复按钮状态
      setTimeout(() => {
        this.isLoading = false
        
        // 生成模拟日志
        const logs = this.generateMockLogs(row)
        
        // 记录该用例有日志可查看
        this.$set(this.hasLogs, row.id, true)
        
        this.$message({
          message: '用例运行完成',
          type: 'success'
        })
      }, 3000)
    },
    handleViewLogs(row) {
      // 查看日志
      this.currentCase = row
      // 模拟获取日志数据
      this.currentLogs = this.generateMockLogs(row)
      this.logDialogVisible = true
    },
    handleClose(done) {
      // 关闭对话框前的处理
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    handleSave() {
      // 保存编辑的数据
      const index = this.tableData.findIndex(item => item.id === this.editForm.id)
      if (index !== -1) {
        this.tableData[index] = { ...this.editForm }
        this.originalTableData = [...this.tableData]
        this.dialogVisible = false
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }
    },
    handleCloseLogDialog(done) {
      done()
    },
    generateMockLogs(row) {
      // 生成模拟日志内容
      const timestamp = new Date().toISOString()
      return `[${timestamp}] 开始执行用例: ${row.id} - ${row.apiName}
[${timestamp}] 测试点: ${row.testPoint}
[${timestamp}] 预期结果: ${row.expectedResult}
[${timestamp}] 发送请求: ${row.apiName}
[${timestamp}] 请求方法: POST
[${timestamp}] 请求头: Content-Type: application/json
[${timestamp}] 请求体: {"param1": "value1", "param2": "value2"}
[${timestamp}] 响应状态码: 200
[${timestamp}] 响应数据: {"status": "success", "data": {"id": ${row.id}, "result": "操作成功"}}
[${timestamp}] 断言结果: 通过
[${timestamp}] 用例执行完成: 成功`
    }
  }
}
</script>

<style scoped>
.apicase-container {
  padding: 20px 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
}

.search-section {
  margin-bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
}

/* 表格样式 */
:deep(.el-table) {
  background-color: transparent !important;
  border: none !important;
}

:deep(.el-table__inner-wrapper),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  background-color: transparent !important;
}

:deep(.el-table::before),
:deep(.el-table::after) {
  display: none !important;
}

:deep(.el-table__header th.el-table__cell),
:deep(.el-table__body td.el-table__cell) {
  background-color: transparent !important;
  border: none !important;
  padding: 12px 0;
}

:deep(.el-table__body tr:hover > td.el-table__cell) {
  background-color: transparent !important;
}

:deep(.el-table__body tr.hover-row > td.el-table__cell) {
  background-color: transparent !important;
}

:deep(.el-table__row--striped td) {
  background-color: transparent !important;
}

/* 对话框样式 */
:deep(.el-dialog) {
  background: transparent !important;
  box-shadow: none !important;
  margin-top: 8vh !important;
}

:deep(.el-dialog__header) {
  padding: 15px 20px !important;
  background: transparent !important;
  border-bottom: none !important;
}

:deep(.el-dialog__body) {
  padding: 10px 20px !important;
  background: transparent !important;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px !important;
  background: transparent !important;
  border-top: none !important;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  color: #606266;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  background: transparent !important;
  border: 1px solid #DCDFE6;
}

:deep(.el-button) {
  padding: 8px 15px;
  font-size: 12px;
  border-radius: 3px;
  margin-left: 10px;
}

:deep(.el-button--text) {
  border: none;
  padding: 0;
  margin: 0 5px;
  color: #409EFF;
}

:deep(.el-button--text:hover) {
  color: #66b1ff;
}

:deep(.el-button--text:focus) {
  color: #409EFF;
}

:deep(.el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

/* 移除所有固定列的背景和边框 */
:deep(.el-table__fixed-right::before),
:deep(.el-table__fixed::before) {
  display: none !important;
}

:deep(.el-table__fixed-right),
:deep(.el-table__fixed) {
  background-color: transparent !important;
  box-shadow: none !important;
}

:deep(.el-table__fixed-right .el-table__fixed-header-wrapper),
:deep(.el-table__fixed .el-table__fixed-header-wrapper),
:deep(.el-table__fixed-right .el-table__fixed-body-wrapper),
:deep(.el-table__fixed .el-table__fixed-body-wrapper) {
  background-color: transparent !important;
}

:deep(.el-table__fixed-right .el-table__cell),
:deep(.el-table__fixed .el-table__cell) {
  background-color: transparent !important;
}

/* 搜索栏样式 */
:deep(.el-select),
:deep(.el-input) {
  margin-right: 10px;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: transparent !important;
  border-color: #DCDFE6;
}

/* 分页器样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}

:deep(.el-pagination button),
:deep(.el-pagination span) {
  background-color: transparent !important;
}

/* 修复表格高度和滚动 */
:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  height: calc(100vh - 250px);
}

:deep(.el-table__empty-block) {
  background-color: transparent !important;
}

:deep(.el-table__empty-text) {
  color: #909399;
}

/* 添加空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
}

/* 加载中遮罩层样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-image {
  width: 80px;
  height: 80px;
  animation: spin 2s infinite linear;
  margin-bottom: 15px;
}

.loading-text {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 日志样式 */
.log-content {
  max-height: 400px;
  overflow-y: auto;
  background-color: #ffffff;
  border-radius: 4px;
  padding: 15px;
  border: 1px solid #e0e0e0;
}

.log-pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: 'Courier New', Courier, monospace;
  color: #00b300;
  font-size: 14px;
  line-height: 1.5;
}

.no-logs {
  padding: 20px;
  text-align: center;
  color: #909399;
}
</style>
